Page({
  data: {
    contractId: '',
    points: [],
    context: null,
    canvas: null
  },

  onLoad(options) {
    this.data.contractId = options.contractId
    this.initCanvas()
  },

  // 初始化画布
  async initCanvas() {
    const query = wx.createSelectorQuery()
    query.select('#signatureCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        
        // 设置画布大小
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        
        // 设置画笔样式
        ctx.strokeStyle = '#000000'
        ctx.lineWidth = 4
        ctx.lineCap = 'round'
        ctx.lineJoin = 'round'

        this.setData({
          context: ctx,
          canvas: canvas
        })
      })
  },

  // 开始触摸
  handleTouchStart(e) {
    const { x, y } = e.touches[0]
    this.data.points = [[x, y]]
    this.data.context.beginPath()
    this.data.context.moveTo(x, y)
  },

  // 触摸移动
  handleTouchMove(e) {
    const { x, y } = e.touches[0]
    this.data.points.push([x, y])
    const ctx = this.data.context
    
    ctx.lineTo(x, y)
    ctx.stroke()
  },

  // 触摸结束
  handleTouchEnd() {
    this.data.context.closePath()
  },

  // 清除签名
  clearSignature() {
    const ctx = this.data.context
    const canvas = this.data.canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    this.data.points = []
  },

  // 保存签名
  async saveSignature() {
    if (this.data.points.length === 0) {
      wx.showToast({
        title: '请先签名',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '保存中' })

    try {
      // 获取签名图片
      const tempFilePath = await this.canvasToImage()
      
      // 上传签名图片
      const signatureUrl = await this.uploadSignature(tempFilePath)
      
      // 提交签署信息
      await this.submitSignature(signatureUrl)

      wx.showToast({
        title: '签署成功',
        icon: 'success'
      })

      // 返回合同详情页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    } catch (error) {
      wx.showToast({
        title: '签署失败',
        icon: 'none'
      })
    }
  },

  // 将画布转换为图片
  canvasToImage() {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        canvas: this.data.canvas,
        success: res => resolve(res.tempFilePath),
        fail: reject
      })
    })
  },

  // 上传签名图片
  uploadSignature(tempFilePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'your-api-url/upload/signature',
        filePath: tempFilePath,
        name: 'signature',
        success: res => {
          const data = JSON.parse(res.data)
          resolve(data.url)
        },
        fail: reject
      })
    })
  },

  // 提交签署信息
  submitSignature(signatureUrl) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'your-api-url/contract/sign',
        method: 'POST',
        data: {
          contractId: this.data.contractId,
          signatureUrl: signatureUrl
        },
        success: resolve,
        fail: reject
      })
    })
  }
}) 